package com.ayu.shortlink.engine.schedule;

import com.alibaba.fastjson2.JSON;
import com.ayu.shortlink.engine.dao.entity.CouponTemplateDO;
import com.ayu.shortlink.engine.dao.mapper.CouponTemplateMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.ayu.shortlink.engine.common.constant.RedisCacheConstant.COUPON_HOT_RANK_KEY;

/**
 * 定时同步Redis热度 -> MySQL
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SyncHotRankTask {
    private final StringRedisTemplate stringRedisTemplate;
    private final CouponTemplateMapper couponTemplateMapper;

    @XxlJob("syncHotRankTask")
    @Transactional(rollbackFor = Exception.class)
    public void handler(){
        Cursor<ZSetOperations.TypedTuple<String>> scan = stringRedisTemplate.opsForZSet().scan(COUPON_HOT_RANK_KEY, ScanOptions.NONE);

        List<CouponTemplateDO> couponTemplateDOList = new ArrayList<>();
        while(scan.hasNext()){
            ZSetOperations.TypedTuple<String> next = scan.next();

            String str = next.getValue();
            Double score = next.getScore();

            CouponTemplateDO couponTemplateDO = JSON.parseObject(str, CouponTemplateDO.class);
            if (couponTemplateDO != null) {
                couponTemplateDO.setHotScore(score);
                couponTemplateDOList.add(couponTemplateDO);
            }
        }
        // 批量持久化
        if (!couponTemplateDOList.isEmpty()){
            couponTemplateMapper.updateById(couponTemplateDOList);
        }
    }
}
